package tech.horgee.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import tech.horgee.common.MyCode;
import tech.horgee.common.MyResult;
import tech.horgee.dto.LoginDTO;
import tech.horgee.entity.User;
import tech.horgee.service.UserService;
import tech.horgee.utils.RsaUtil;

import java.io.IOException;
import java.util.Optional;

/**
 * 鉴权接口
 *
 * @author haojun
 * @since 2022-06-12
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class AuthController {
    private final UserService userService;

    /**
     * 登陆
     *
     * @param user    登陆信息
     * @param session session
     */
    @PostMapping("login")
    public MyResult login(@RequestBody LoginDTO user, HttpSession session) {
        Optional.ofNullable((ICaptcha) session.getAttribute("captcha")).ifPresent(captcha -> {
            log.info("verify captcha: {} - {} [{}]", user.getCaptcha(), captcha.getCode(), captcha.verify(user.getCaptcha()));
            if (!captcha.verify(user.getCaptcha())) {
                throw MyCode.ERROR_CAPTCHA.toException();
            }
        });
        String username = user.getUsername();
        String password = user.getPassword();
        Optional<User> opt = userService.getByUsername(username);
        if (opt.isPresent()) {
            User info = opt.get();
            if (RsaUtil.decrypt(info.getPassword()).equals(password)) {
                if (info.getLocked()) {
                    throw MyCode.LOCKED_ACCOUNT.toException();
                }
                StpUtil.login(info.getUserId());
            } else {
                throw MyCode.ERROR_PASSWORD.toException();
            }
        } else {
            throw MyCode.UNKNOWN_ACCOUNT.toException();
        }
        return MyResult.of(StpUtil.getTokenInfo());
    }

    /**
     * 登出
     */
    @PostMapping("logout")
    public MyResult logout() {
        StpUtil.logout();
        return MyResult.success();
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("current")
    public MyResult getCurrent() {
        Long loginId = StpUtil.getLoginIdAsLong();
        return MyResult.of(userService.getById(loginId));
    }

    /**
     * 获取验证码
     *
     * @param response 验证码
     * @param session  session
     * @throws IOException IOException
     */
    @GetMapping("captcha")
    public void captcha(HttpServletResponse response, HttpSession session) throws IOException {
        RandomGenerator generator = new RandomGenerator("23456789abdefghjmnqrtABDEFGHJMNQRT", 4);
        GifCaptcha captcha = CaptchaUtil.createGifCaptcha(200, 100, 4);
        captcha.setGenerator(generator);
        captcha.createCode();
        String code = captcha.getCode();
        log.info("gen captcha: {}", code);
        session.setAttribute("captcha", captcha);
        response.setContentType("image/gif");
        ServletOutputStream out = response.getOutputStream();
        captcha.write(out);
        out.close();
    }
}
